<template>
  <div>
    <Card :bordered="false">
      <Row>
        <Col span="12">
        <ButtonGroup>
          <Button type="primary" @click="openAddAccount">新增</Button>
        </ButtonGroup>
        </Col>
        <Col span="12" style="text-align: right">
        <Input v-model="txtSearch" placeholder="请输入用户名称" style="width: 200px"/>
        <Button icon="ios-search" type="primary" @click="getAccountList()"></Button>
        </Col>
      </Row>
    </Card>
    <Card :bordered="false">
      <Table stripe height="500" :columns="columns" :data="accountList"></Table>
    </Card>
    <!--新增账户-->
    <Modal
      v-model="modal.add.status"
      :title="modal.add.title"
      :top="0" @on-cancel="modalDefineCancel('modal.add.form')">
      <Form ref= 'modal.add.form' :model="modal.add.form" :label-width="80" :rules='ruleValidate'>
        <FormItem label="登录名称" prop='loginName'>
          <Input v-model="modal.add.form.loginName" placeholder="如不设置，账户无法登录系统" @on-blur="checkLoginName(modal.add.form.loginName)"></Input>
          <label class="codeLb" v-if="loginNameError">登录名称已存在</label>
        </FormItem>
        <FormItem label="登录密码" prop='password'>
          <Input type="password" v-model="modal.add.form.password" placeholder="密码长度不少于6位"></Input>
        </FormItem>
        <FormItem label="用户名称" prop='userName':label-width="82" >
          <Input v-model="modal.add.form.userName" placeholder="请输入用户名称"></Input>
        </FormItem>
        <FormItem label="所在机构" prop='orgId'>
          <Select clearable v-model="modal.add.form.orgId" style="width:100%;text-align: left">
            <Option v-for="item in orgList" :value="item.id" :key="item.orgName">{{ item.orgName }}</Option>
          </Select>
        </FormItem>
        <FormItem label="用户类别" >
          <Input v-show="$store.state.user.superFlag==1" disabled v-model="userTypeAdmin"></Input>
          <Input v-show="$store.state.user.superFlag==0" disabled v-model="userType"></Input>
        </FormItem>
        <FormItem label="邮箱" prop='email'>
          <Input v-model="modal.add.form.email" placeholder="请输入邮箱"></Input>
        </FormItem>
        <FormItem label="电话" prop='telephone'>
          <Input v-model="modal.add.form.telephone" placeholder="请输入电话"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="handleReset('modal.add.form')">取消</Button>
        <Button type="primary" @click="handleSubmit('modal.add.form')">确定</Button>
      </div>
    </Modal>
    <!--修改账户-->
    <Modal
      v-model="modal.update.status"
      :title="modal.update.title"
      :top="0" @on-cancel="modalDefineCancel('modal.update.form')">
      <Form ref= 'modal.update.form' :model="modal.update.form" :label-width="80" :rules='ruleValidate'>
        <FormItem label="登录名称" prop='loginName'>
          <Input disabled v-model="modal.update.form.loginName"></Input>
        </FormItem>
        <FormItem label="登录密码" hidden>
          <Input type="password" v-model="modal.update.form.password"></Input>
        </FormItem>
        <FormItem label="用户名称" prop='userName' :label-width="82">
          <Input v-model="modal.update.form.userName" placeholder="请输入用户名称"></Input>
        </FormItem>
        <!--<FormItem label="用户姓名" v-if="$store.state.user.superFlag==0" prop='userName'>
          <Input v-model="modal.update.form.userName" placeholder="请输入用户姓名"></Input>
        </FormItem>-->
        <FormItem label="所在机构" prop='orgId'>
          <Select clearable v-model="modal.update.form.orgId" style="width:100%;text-align: left">
            <Option v-for="item in orgList" :value="item.id" :key="item.orgName">{{ item.orgName }}</Option>
          </Select>
        </FormItem>
        <FormItem label="用户类别" >
          <Input v-show="modal.update.form.superFlag==0 || modal.update.form.superFlag==1" disabled v-model="userTypeAdmin"></Input>
          <Input v-show="modal.update.form.superFlag==2" disabled v-model="userType"></Input>
        </FormItem>
        <FormItem label="邮箱" prop='email'>
          <Input v-model="modal.update.form.email" placeholder="请输入邮箱"></Input>
        </FormItem>
        <FormItem label="电话" prop='telephone'>
          <Input v-model="modal.update.form.telephone" placeholder="请输入电话"></Input>
        </FormItem>

      </Form>
      <div slot="footer">
        <Button type="default" @click="handleReset('modal.update.form')">取消</Button>
        <Button type="primary" @click="handleSubmit('modal.update.form')">确定</Button>
      </div>
    </Modal>
    <!--删除账户-->
    <Modal
      v-model="modal.delete.status"
      :title="modal.delete.title">
      确定删除账户{{modal.delete.loginName}}吗？
      <div slot="footer">
        <Button type="default" @click="modal.delete.status=false">取消</Button>
        <Button type="error" @click="deleteAccount">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import urlSource from '../../api/urlSource'

  export default {
    name: "index",
    components: {},
    data() {
      let validateLoginName = function(rule, value, callback){
        if(!value){
          return callback(new Error("请输入登录名称"));
        }else if(!/^[a-zA-Z\d]+$/.test(value)){
          return callback(new Error("请正确输入登录名称"))
        }else{
          callback();
        }
      };

      let validatePassword = function(rule, value, callback){
        if(!value){
          return callback(new Error("请输入密码"));
        }else if(value.length < 6){
          return callback(new Error("密码长度不少于6位"))
        }else{
          callback();
        }
      };
      let validateUserName = function(rule, value, callback){
        if(!value){
          return callback(new Error("请输入用户名称"));
        }else{
          callback();
        }
      };
      let validateOrgId = function(rule, value, callback){
        if(!value){
          return callback(new Error("请选择机构"));
        }else{
          callback();
        }
      };
      let validateEmail = function (rule, value, callback) {
        if(value && !/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(value)){
          return callback(new Error("邮箱格式错误"))
        }else{
          callback();
        }
      };
      let validateTelephone = function (rule, value, callback) {
        if(value && !/^1[0-9]{10}$/.test(value)){
          if(!/^0\d{2,3}-?\d{7,8}$/.test(value)){
            return callback(new Error("号码格式错误"))
          }
        }else{
          callback();
        }
      };

      return {
        modal: {
          add: {
            status: false,
            title: "新增用户",
            form: {
              id: "",
              loginName: "",
              password: "",
              telephone: "",
              userName: "",
              remark: "",
              createTime: "",
              email: "",
              address: "",
              code: "",
              unitName: "",
            }
          },
          update: {
            status: false,
            title: "修改用户",
            form: {
              id: "",
              loginName: "",
              password: "",
              telephone: "",
              userName: "",
              remark: "",
              createTime: "",
              email: "",
              address: "",
              code: "",
              unitName: "",
            }
          },
          delete: {
            status: false,
            title: "系统提示",
            LoginName: "",
            id: ""
          }
        },
        txtSearch: "",
        columns: [
          {
            type: 'index',
            width: 60,
            align: 'center'
          },
          {
            title: '用户名称',
            key: 'userName'
          },
          {
            title: '登录名称',
            key: 'loginName'
          },
          {
            title:'机构',
            key: 'orgId',
            render: (h,params) =>{
              let orgName = '';
              this.orgList.forEach((data) => {
                if(data.id == params.row.orgId){
                  orgName = data.orgName;
                }
              });
              return h('div',[
                h('div',orgName)
              ]);
            }
          },
          {
            title: '电话',
            key: 'telephone'
          },
          {
            title: '邮箱',
            key: 'email'
          },
          {
            title: '操作',
            width: 280,
            key: 'id',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.modal.update.status = true;
                      this.modal.update.form = JSON.parse(JSON.stringify(params.row));
                    }
                  }
                }, '修改'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.modal.delete.status = true;
                      this.modal.delete.loginName = params.row.loginName;
                      this.modal.delete.id = params.row.id;
                    }
                  },
                  style: {
                    display: params.row.superFlag == 1 ? "none" : this.$store.state.user.superFlag == 0 && params.row.superFlag == 0 ? "none" : "inline-block"
                  }
                }, '删除')
              ]);
            }
          },
        ],
        ruleValidate:{
         loginName : [{required: true,validator: validateLoginName,trigger: 'blur'}],
         password : [{required: true,validator: validatePassword,trigger: 'blur'}],
          userName : [{required: true,validator: validateUserName,trigger: 'blur'}],
          orgId : [{required: true,validator: validateOrgId,type: 'string', message: '请选择机构',trigger: 'change'}],
          email: [{required: false,validator:validateEmail,type:'string',trigger:'blur'}],
          telephone: [{required: false,validator:validateTelephone,type:'string',trigger:'blur'}],
          /*userType: [{required: true,validator:validateUserType,type:'string',trigger:'blur'}]*/
        },
        accountList: [],
        orgList: [],
        loginNameError: false,
        userTypeAdmin: '管理员',
        userType: '普通用户'
      }
    },
    methods: {
      handleReset (name) {
        if(name=='modal.add.form'){
          this.modal.add.status=false;
        }else{
          this.modal.update.status=false;
        }
        this.loginNameError = false;
        this.$refs[name].resetFields();
      },
      modalDefineCancel (name){
        this.loginNameError = false;
        this.$refs[name].resetFields();
      },
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            if(this.loginNameError){
              this.$Message.error('请正确填写登录名称');
              return;
            }
            if(name=='modal.add.form'){//添加表单校验
              this.addAccount();
            }else{//修改表单校验
              this.updateAccount();
            }
          } else {
            this.$Message.error('请正确填写信息');
          }
        })
      },
      //获取机构
      getOrgList(superFlag){
        let url = '';
        if(superFlag==1){//如果是超级管理员添加人员，则默认显示根机构和一级机构
          url = urlSource.apiUrl + 'org/getSecondOrg';
          this.$http.get(url).then(res => {
            this.orgList = res.data;
          });
        }else{//显示当前机构及其子机构
          let currentOrgId = this.$store.state.user.orgId;
          url = urlSource.apiUrl + 'org/getParentOrg/' + currentOrgId;
          this.$http.get(url).then(res => {
            this.orgList = res.data;
          }).catch(err => {

          })
        }
      },
      //获取账户列表
      getAccountList() {
        /*let url = urlSource.apiUrl + "users/"+this.$store.state.user.orgId+"/all/";
        this.$http.get(url).then(res => {
          this.accountList = res.data;
        }).catch(err => {

        })*/
        let url = urlSource.apiUrl + "users/all";
        this.$http.post(url,{orgId:this.$store.state.user.orgId,userName:this.txtSearch,superFlag:this.$store.state.user.superFlag}).then(res => {
          this.accountList = res.data;
        }).catch(err => {

        });
      },
      //打开新增账户
      openAddAccount() {
        this.modal.add.status = true;
      },

      /**
       * 修改账户
       */
      updateAccount() {
        let url = urlSource.apiUrl + "users/update";
        if(this.$store.state.user.superFlag==1){
          this.modal.update.form.superFlag = 0;
        }else if(this.$store.state.user.superFlag==0){
          this.modal.update.form.superFlag = 2;
        }else{
          // do nothing
        }
        this.$http.put(url, this.modal.update.form).then(res => {
          if (res.data) {
            this.modal.update.status = false;
            this.$Message.success("修改成功!")
            this.getAccountList();
          } else {
            this.$Message.error("修改失败!")
          }
        }).catch(err => {
          this.$Message.error("修改失败!")
        })
      },
      //添加账户
      addAccount() {
        let url = urlSource.apiUrl + "users/add";
        if(this.$store.state.user.superFlag==1){
          this.modal.add.form.superFlag = 0;
        }else if(this.$store.state.user.superFlag==0){
          this.modal.add.form.superFlag = 2;
        }else{
          // do nothing
        }
        this.$http.post(url, this.modal.add.form).then(res => {
          if (res.data) {
            this.modal.add.status = false;
            this.$Message.success("新增成功!")
            this.getAccountList();
            this.$refs['modal.add.form'].resetFields();
          } else {
            this.$Message.error("新增失败!")
          }
        }).catch(err => {
          this.$Message.error("新增失败!")
        })
      },
      //删除账户
      deleteAccount() {
        let url = urlSource.apiUrl + "users/delete/" + this.modal.delete.id;
        this.$http.delete(url).then(res => {
          if (res.data) {
            this.$Message.success("删除成功!")
            this.getAccountList();
            this.modal.delete.status = false;
          } else {
            this.$Message.error("删除失败!")
          }
        }).catch(err => {
          this.$Message.error("删除失败!")
        })
      },
      checkLoginName(loginName){
        if(loginName){
          let url = urlSource.apiUrl + "users/checkLoginName";
          this.$http.post(url,{loginName:loginName}).then(res => {
            if(res.data){
              this.loginNameError = true;
            }else{
              this.loginNameError = false;
            }
          }).catch(err => {

          })
        }else{
          this.loginNameError = false;
        }
      },
    },
    mounted() {
      this.$nextTick(() => {
        this.getOrgList(this.$store.state.user.superFlag);
        this.getAccountList();
      })
    }
  }
</script>

<style lang="less">
  .vertical-center-modal {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .ivu-modal {
    top: 2px;
  }
  .codeLb{
    position: absolute;
    padding-top: 6px;
    line-height: 1;
    color: #ed3f14;
    top: 100%;
    left: 0;
  }
</style>
